package admin

import (
	"blog/models"
	"fmt"

	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

type ArticleController struct {
	BaseAdminController
}

func (con ArticleController) Index(c *gin.Context) {
	// c.String(http.StatusOK, "文章列表--")
	con.success(c, "ok")
}
func (con ArticleController) List(c *gin.Context) {
	pageSize := c.DefaultQuery("size", "10")
	page := c.DefaultQuery("page", "1")
	limitInt, err := strconv.Atoi(pageSize)
	cat_query := c.DefaultQuery("cat", "0")

	if err != nil || limitInt < 0 {
		limitInt = 4
	}
	pageNumberInt, err := strconv.Atoi(page)
	if err != nil || limitInt < 0 {
		pageNumberInt = 1
	}
	start := (pageNumberInt - 1) * limitInt

	where := ""
	if cat_query != "0" {
		where = " where cat = " + cat_query
	}

	sql_count := "select count(*) as count from fa_article " + where
	count := models.Selects(sql_count)

	count_articles, err := strconv.Atoi(count[0]["count"])
	pages := int(count_articles/limitInt) + 1

	pages_all := make([]int, pages+1)
	for i := 1; i <= pages; i++ {
		pages_all[i] = i
	}
	//分类
	rowscat, err := models.Db.Query("SELECT *  FROM fa_cat")
	if err != nil {
		con.error(c, err.Error())
		return
	}
	defer rowscat.Close()
	cats := make(map[string]string)
	for rowscat.Next() {
		var id int
		var cname string
		rowscat.Scan(&id, &cname)
		ids := fmt.Sprintf("%v", id)
		cats[ids] = fmt.Sprintf("%v", cname)
	}

	//sql := "SELECT * FROM  fa_article limit  " + start + " ," + limitInt + " order by id desc"

	rows, err := models.Db.Query("SELECT  `title`, `cat`, `cat1`, `cat2`, `fei`, `post_time`, `id`,`clicks`,`hot`,`top` FROM  fa_article "+where+" order by id desc limit   ? , ? ", start, limitInt)
	if err != nil {
		con.error(c, err.Error())
		return
	}
	defer rows.Close()
	result := make(map[int]map[string]string)
	i := 0
	for rows.Next() {
		var title, cat, cat1, cat2, fei, post_time, id, clicks, hot, top string

		rows.Scan(&title, &cat, &cat1, &cat2, &fei, &post_time, &id, &clicks, &hot, &top)
		row := make(map[string]string)
		row["id"] = id
		row["title"] = fmt.Sprintf("%v", title)
		row["cat"] = cat
		row["cat1"] = cat1
		row["cat2"] = cat2
		if cat == "0" {
			row["catname"] = ""
		} else {
			row["catname"] = cats[cat]
		}
		if cat1 == "0" {
			row["cat1name"] = ""
		} else {
			row["cat1name"] = cats[cat1]
		}
		if cat2 == "0" {
			row["cat2name"] = ""
		} else {
			row["cat2name"] = cats[cat2]
		}

		row["fei"] = fei
		row["post_time"] = post_time
		row["clicks"] = clicks
		row["hot"] = hot
		row["top"] = top
		result[i] = row
		i++
	}

	username := con.getAdminName(c)
	page_number, err := strconv.Atoi(page)
	// 下一页
	next := page_number + 1
	if next == pages {
		next = pages
	}
	//上一页
	pre := page_number - 1
	if pre == 0 {
		pre = 1
	}
	c.HTML(http.StatusOK, "admin/article_list.html", gin.H{
		"msg":            "列表页",
		"username":       username,
		"articles":       result,
		"count_articles": count_articles,
		"page":           page_number, //当前第几页
		"pages":          pages,       //总页数
		"pre":            pre,
		"cat_query":      cat_query,
		"pages_all":      pages_all,
		"next":           next,
	})
	// con.success(c, "ok")
}

func (con ArticleController) DoAdd(c *gin.Context) {
	cat := strings.TrimSpace(c.PostForm("class"))
	content := strings.TrimSpace(c.PostForm("content"))
	title := strings.TrimSpace(c.PostForm("title"))
	hot := c.DefaultPostForm("hot", "0")
	top := c.DefaultPostForm("top", "0")
	if title == "" || content == "" || cat == "" {
		c.JSON(200, gin.H{
			"msg": "标题，内容，分类不能为空",
		})
		return
	}

	cat1 := strings.TrimSpace(c.PostForm("class1"))
	cat2 := strings.TrimSpace(c.PostForm("class2"))
	fei := strings.TrimSpace(c.PostForm("experience"))

	if cat1 == "" {
		cat1 = "0"
	}
	if cat2 == "" {
		cat2 = "0"
	}

	post_time := models.GetDate()

	r, err := models.Db.Exec("insert into fa_article(title, cat, cat1,cat2,content,fei,post_time,hot,top)values(?, ?, ?,?,?,?,?,?,?)", title, cat, cat1, cat2, content, fei, post_time, hot, top)
	if err != nil {
		con.error(c, err.Error())
		return
	}
	id, err := r.LastInsertId()
	if err != nil {
		con.error(c, err.Error())
		return
	}
	c.JSON(200, gin.H{
		"msg":    "发布成功:" + strconv.FormatInt(id, 10),
		"status": 0,
		"action": "/admin/article/add",
	})
}
func (con ArticleController) Add(c *gin.Context) {
	username := con.getAdminName(c)
	rows, err := models.Db.Query("SELECT *  FROM fa_cat")
	if err != nil {
		con.error(c, err.Error())
		return
	}
	defer rows.Close()
	result := make(map[int]map[string]string)
	i := 0
	for rows.Next() {
		var id int
		var cname string
		rows.Scan(&id, &cname)
		row := make(map[string]string)
		row["id"] = fmt.Sprintf("%v", id)
		row["cname"] = fmt.Sprintf("%v", cname)
		result[i] = row
		i++
	}
	c.HTML(http.StatusOK, "admin/article_add.html", gin.H{
		"msg":      "发布页",
		"username": username,
		"cat":      result,
	})
}
func (con ArticleController) DoEdit(c *gin.Context) {
	id := strings.TrimSpace(c.PostForm("id"))
	cat := strings.TrimSpace(c.PostForm("class"))
	content := strings.TrimSpace(c.PostForm("content"))
	title := strings.TrimSpace(c.PostForm("title"))
	hot := c.DefaultPostForm("hot", "0")
	top := c.DefaultPostForm("top", "0")
	if title == "" || content == "" || cat == "" {
		c.JSON(200, gin.H{
			"msg": "标题，内容，分类不能为空",
		})
		return
	}
	username := con.getAdminName(c)
	cat1 := strings.TrimSpace(c.PostForm("class1"))
	cat2 := strings.TrimSpace(c.PostForm("class2"))
	fei := strings.TrimSpace(c.PostForm("experience"))

	if cat1 == "" {
		cat1 = "0"
	}
	if cat2 == "" {
		cat2 = "0"
	}

	_, err := models.Db.Exec("update fa_article set title = ?,content =?,fei=?,cat=?,cat1=?,cat2=?,top=?,hot=? where id = ?", title, content, fei, cat, cat1, cat2, top, hot, id)
	if err != nil {
		con.error(c, err.Error())
		return
	}
	c.JSON(200, gin.H{
		"msg":      "编辑成功",
		"status":   0,
		"username": username,
		"action":   "/admin/article/list?v=1",
	})
}

func (con ArticleController) Edit(c *gin.Context) {
	id := c.Param("id")
	article := models.Selects("select * from fa_article where id = " + id)
	if article[0]["title"] == "" {
		con.error(c, "参数错误")
		return
	}

	cats := models.Selects("SELECT *  FROM fa_cat")
	username := con.getAdminName(c)
	c.HTML(http.StatusOK, "admin/article_edit.html", gin.H{
		"msg":      "编辑页",
		"username": username,
		"cat":      cats,
		"article":  article[0],
	})
}
